package com.example.tests;

import static org.junit.Assert.assertTrue;

import java.util.concurrent.TimeUnit;


import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.example.pages.AddMoviePage;
import com.example.pages.HomePage;
import com.example.pages.InternalPage;
import com.example.pages.LoginPage;
import com.example.pages.MovieProfilePage;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import ru.esteru.selenium.factory.WebDriverFactory;

public class AddNewFilm {
	private static WebDriver driver;
	private static WebDriverWait wait;
	private static String baseUrl;
	

	@BeforeClass
	public static void setUp() throws Exception {
		driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
		wait = new WebDriverWait(driver, 10);
		baseUrl = "http://localhost/";
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
	}

	public LoginPage loginPage;
	public InternalPage somePage;
	public HomePage homePage;
	public AddMoviePage addMoviePage;
	public MovieProfilePage movieProfilePage;

	@Test
	public void testAddingMovie() {

		goToMainPage();
		loginAs("admin", "admin");
		String movieName = "Thor";
		String movieYear = "2011";
		addMovie(movieName, movieYear);
		logOut();

	}

	private void addMovie(String movieName, String movieYear) {
		homePage.addNewMovieButton.click();
		addMoviePage.movieNameField.clear();
		addMoviePage.movieNameField.sendKeys(movieName);
		addMoviePage.movieYearField.clear();
		addMoviePage.movieYearField.sendKeys(movieYear);
		addMoviePage.saveButton.click();
		assertTrue("Page of created film doesn't exist",
				movieProfilePage.isFilmProfilePageOpened(movieName));

	}

	private void loginAs(String userName, String password) {

		loginPage.userNameField.clear();
		loginPage.userNameField.sendKeys(userName);
		loginPage.passwordField.clear();
		loginPage.passwordField.sendKeys(password);
		loginPage.loginButton.click();
	}

	private void goToMainPage() {
		driver.get(baseUrl + "/php4dvd/");
		loginPage = PageFactory.initElements(driver, LoginPage.class);
		homePage = PageFactory.initElements(driver, HomePage.class);
		addMoviePage = PageFactory.initElements(driver, AddMoviePage.class);
		somePage = PageFactory.initElements(driver, InternalPage.class);
		movieProfilePage = PageFactory.initElements(driver,
				MovieProfilePage.class);
	}

	private void logOut() {
		somePage.menuLogoutLink.click();
		wait.until(alertIsPresent()).accept();
	}

	}
